package io.kimmking.rpcfx.metadata.center.zookeeper;

import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.metadata.center.ParseServiceUtil;
import io.kimmking.rpcfx.metadata.center.api.MetadataRegister;
import io.kimmking.rpcfx.metadata.center.api.Server;
import io.kimmking.rpcfx.register.center.api.ProviderInfo;
import io.kimmking.rpcfx.register.center.api.Register;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;


/**
 * @author lfy
 */
public class ZookeeperMetadataRegister implements MetadataRegister {


    private CuratorFramework client;
    private final String zookeeperServer;
    private final String namespace;

    public ZookeeperMetadataRegister(String server, String namespace) {
        this.zookeeperServer = server;
        this.namespace = namespace;
        init();
    }
    public CuratorFramework getClient() {
        return client;
    }
    private void init() {
        // start zk client
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder().connectString(zookeeperServer)
                .namespace(namespace).retryPolicy(retryPolicy).build();
        client.start();
    }



    @Override
    public void register(String serviceName) {
        try {
            Server server = ParseServiceUtil.parse(serviceName);
            client.create().withMode(CreateMode.EPHEMERAL).forPath("/" + serviceName,
                    JSON.toJSONString(server).getBytes()
            );
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
}
